package com.imooc.demo.Controller;

import com.imooc.demo.API.FFMpegTest;
import com.imooc.demo.API.MergeVideoBgm;
import com.imooc.demo.API.VideoStatusEnum;
import com.imooc.demo.Model.bgm;
import com.imooc.demo.Model.users;
import com.imooc.demo.Model.videos;
import com.imooc.demo.Service.BgmService;
import com.imooc.demo.Service.VideoService;
import com.imooc.demo.Util.IMoocJSONResult;
import com.imooc.demo.idworker.strategy.FileLock;
import io.swagger.annotations.*;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Administrator
 * @version : 1.0
 * @auther : hjx
 * @Date : 2021/2/1
 * @Description : nuc.edu.hjx.controller
 */
@RestController
@RequestMapping("/video")
@Api(value = "视频接口", tags = "视频相关业务接口")
public class VideoController extends BasicController{

    @Resource
    private BgmService bgmService;
    @Resource
    private VideoService videoService;

    @ApiOperation(value = "上传视频", notes = "上传视频接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户Id",required = true,dataType = "Integer",paramType = "form"),
            @ApiImplicitParam(name = "bgmId",value = "bgmId",dataType = "Integer",paramType = "form"),
            @ApiImplicitParam(name = "videoSecound",value = "视频时长",required = true,dataType = "String",paramType = "form"),
            @ApiImplicitParam(name = "videoWidth",value = "视频宽度",required = true,dataType = "String",paramType = "form"),
            @ApiImplicitParam(name = "videoHeight",value = "视频长度",required = true,dataType = "String",paramType = "form"),
            @ApiImplicitParam(name = "desc",value = "视频描述",dataType = "String",paramType = "form"),
    })
    @PostMapping(value = "/uploadvideo", headers ="content-type=multipart/form-data")
    public IMoocJSONResult uploadVideo(Integer userId, Integer bgmId, double videoSecound, int videoWidth, int videoHeight,
                                       String desc, @ApiParam(value = "视频文件",required = true)MultipartFile file) throws Exception {
        if (userId.equals(null)){//StringUtils.isBlank(userId)
            return IMoocJSONResult.errorMsg("用户id不能为空");
        }
        //文保存的明明空间
        //String fileSpace = "G:/ij_program1";
        //保存奥数据库中的相对路径
        String uploadPathDB = "/" + userId + "/video";
        String coverPathDB= "/" + userId + "/video";

        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;

        String finalVideoPath="";
        try{
            if (file != null ) {
                //xxx.mp4视频名字
                String fileName = file.getOriginalFilename();
                String fileNamePrefix=fileName.split("\\.")[0];
                if (StringUtils.isNoneBlank(fileName)) {
                    //文件上传的最终保存路径
                    finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
                    uploadPathDB += ("/" + fileName);
                    //图像上传路径
                    coverPathDB=coverPathDB+"/"+fileNamePrefix+".jpg";
                    File outFile = new File(finalVideoPath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            }else {
                return IMoocJSONResult.errorMsg("上传出错");
            }
        }catch (Exception e){
            e.printStackTrace();
            return IMoocJSONResult.errorMsg("上传出错");
        }finally {
            if (fileOutputStream!=null){
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        if (bgmId!=null){
            bgm bgm=bgmService.queryByBgmId(bgmId);
            String mp3InputPath=FILE_SPACE+bgm.getPath();

            //String ffmpegXE="D:\\ffmpeg\\bin\\ffmpeg.exe";
            FFMpegTest tool=new FFMpegTest(FFMPEG_EXE);
            String videoInputPath=finalVideoPath;

            String videoOutputName=UUID.randomUUID().toString()+".mp4";
            uploadPathDB="/"+userId+"/video"+"/"+videoOutputName;
            finalVideoPath=FILE_SPACE+uploadPathDB;
            tool.convertor(videoInputPath,mp3InputPath,videoSecound,finalVideoPath);
        }
        System.out.println("uploadPathDB"+uploadPathDB);
        System.out.println("finalVideoPath"+finalVideoPath);

        //对视频进行截图
        FFMpegTest videoInfo=new FFMpegTest(FFMPEG_EXE);
        videoInfo.getcover(finalVideoPath,FILE_SPACE+coverPathDB);

        videos video = new videos();
        video.setAudio_id(bgmId);
        video.setUser_id(userId);
        video.setVideo_desc(desc);
        video.setVideo_path(uploadPathDB);
        video.setVideo_seconds((float)videoSecound);
        video.setVideo_width(videoWidth);
        video.setVideo_height(videoHeight);
        video.setCover_path(coverPathDB);
        video.setStatus(VideoStatusEnum.SUCCESS.value);
        video.setCreate_time(new Date());

        Integer videoId=videoService.saveVideo(video);

        return IMoocJSONResult.ok(videoId);
    }


    @ApiOperation(value = "上传封面", notes = "上传封面的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoId",value = "视频主键id",required = true,dataType = "Integer",paramType = "form"),
            @ApiImplicitParam(name = "userId",value = "用户id",required = true,dataType = "Integer",paramType = "form"),
    })
    @PostMapping(value = "/uploadCover", headers ="content-type=multipart/form-data")
    public IMoocJSONResult uploadCover(Integer userId,Integer videoId, @ApiParam(value = "视频封面",required = true)MultipartFile file) throws Exception {
        if (userId.equals(null)||videoId.equals(null)){//StringUtils.isBlank(userId)
            return IMoocJSONResult.errorMsg("用户id和视频id不能为空");
        }
        //文保存的明明空间
        //String fileSpace = "G:/ij_program1";
        //保存奥数据库中的相对路径
        String uploadPathDB = "/" + userId + "/video";
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;

        String finalVideoPath="";
        try{
            if (file != null ) {
                String fileName = file.getOriginalFilename();
                if (StringUtils.isNoneBlank(fileName)) {
                    //文件上传的最终保存路径
                    finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
                    uploadPathDB += ("/" + fileName);
                    File outFile = new File(finalVideoPath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            }else {
                return IMoocJSONResult.errorMsg("上传出错");
            }
        }catch (Exception e){
            e.printStackTrace();
            return IMoocJSONResult.errorMsg("上传出错");
        }finally {
            if (fileOutputStream!=null){
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }

        videoService.upateVideo(videoId,uploadPathDB);
        return IMoocJSONResult.ok();
    }

//    @Resource
//    private BgmService bgmService;
//    @Resource
//    private VideoService videoService;
//    @Resource
//    private RecordService recordService;

    /**
     * 上传视频接口
     * @param userId
     * @param bgmId
     * @param videoSecound
     * @param videoWidth
     * @param videoHeight
     * @param desc
     * @param file
     * @return
     */
//    @ApiOperation(value = "上传视频", notes = "上传视频接口")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userId",value = "用户Id",required = true,dataType = "String",paramType = "form"),
//            @ApiImplicitParam(name = "bgmId",value = "bgmId",dataType = "String",paramType = "form"),
//            @ApiImplicitParam(name = "videoSecound",value = "视频时长",required = true,dataType = "String",paramType = "form"),
//            @ApiImplicitParam(name = "videoWidth",value = "视频宽度",required = true,dataType = "String",paramType = "form"),
//            @ApiImplicitParam(name = "videoHeight",value = "视频长度",required = true,dataType = "String",paramType = "form"),
//            @ApiImplicitParam(name = "desc",value = "视频描述",dataType = "String",paramType = "form"),
//    })
//    @PostMapping(value = "/uploadvideo", headers ="content-type=multipart/form-data")
//    public IMoocJSONResult uploadVideo(String userId, String bgmId, double videoSecound, int videoWidth, int videoHeight,
//                                       String desc, @ApiParam(value = "视频文件",required = true)MultipartFile file) throws Exception {
//        //判断userId是否为空
//        if (StringUtils.isBlank(userId)) {
//            return IMoocJSONResult.errorMsg("账号不能为空！");
//        }
//        //获取文件的资源路径
//        String uploadDb = "/user/" + userId + "/video/";
//        String filename = file.getOriginalFilename();
//
//        String videoOutputPath = null;
//        String coverPath = null;
//
//        if (StringUtils.isNotBlank(filename)) {
//            File video = new File(USER_PATH + uploadDb + filename);
//            //对文件的父文件夹进行查询，不存在就创建新文件夹
//            if (video.getParentFile() !=null && !video.getParentFile().isDirectory()) {
//                video.getParentFile().mkdirs();
//            }
//            try {
//                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(USER_PATH + uploadDb + filename));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            if (StringUtils.isNotBlank(bgmId)) {
//                Bgm bgm = bgmService.queryByBgmId(bgmId);
//                String bgmPath = USER_PATH + bgm.getPath();
//                MergeVideoBgm tool = new MergeVideoBgm(FFMPEG_EXE);
//                String videoInputPath = USER_PATH + uploadDb + filename;
//                videoOutputPath = uploadDb + UUID.randomUUID().toString() + ".mp4";
//                tool.convert(videoInputPath,bgmPath,USER_PATH + videoOutputPath,videoSecound);
//                video.delete();
//                coverPath = getCoverPath(userId,USER_PATH + videoOutputPath);
//
//            }
//            Videos videos = new Videos();
//            videos.setUserId(userId);
//            videos.setAudioId(bgmId);
//            videos.setVideoSeconds((float)videoSecound);
//            videos.setVideoWidth(videoWidth);
//            videos.setVideoHeight(videoHeight);
//            videos.setVideoDesc(desc);
//            videos.setVideoPath(videoOutputPath);
//            videos.setCoverPath(coverPath);
//            videos.setCreateTime(new Date());
//            videos.setStatus(VideoStatusEnum.SUCCESS.value);
//            videoService.saveVideo(videos);
//            return JSONResult.ok();
//        }
//
//        return JSONResult.errorMsg("上传视频失败！");
//    }

    /**
     * 生成视频前一秒截图当做封面
     * @param userId
     * @param videoIntputPath
     * @return String
     * @throws IOException
     */
//    public String getCoverPath(String userId ,String videoIntputPath) throws IOException {
//        String uploadDb = "/user/" + userId + "/cover/";
//        String covername = UUID.randomUUID().toString() + ".jpg";
//        File cover = new File(USER_PATH + uploadDb + covername);
//        if (cover.getParentFile() !=null && !cover.getParentFile().isDirectory()) {
//            cover.getParentFile().mkdirs();
//        }
//        MergeVideoBgm tool = new MergeVideoBgm(FFMPEG_EXE);
//        tool.getcover(videoIntputPath,USER_PATH + uploadDb + covername);
//        return uploadDb + covername;
//    }
//
//    /**
//     * 获取视频的分页视频信息
//     * @param page
//     * @return
//     */
//    @ApiOperation(value = "获取视频的分页数据",notes = "视频分页数据接口")
//    @PostMapping("/showallvideo")
//    public JSONResult showAllVideos(Integer page) {
//        if (page == null) {
//            page = 1;
//        }
//        PagedResult result = videoService.getAllVideos(page,PAGE_SIZE);
//        return JSONResult.ok(result);
//    }
//
//    /**
//     * 获取搜索视频分页
//     * @param video
//     * @param page
//     * @return
//     */
//    @ApiOperation(value = "搜索视频分页展示",notes = "搜索视频分页展示接口")
//    @PostMapping("/queryvideo")
//    public JSONResult showQueryVideos(@RequestBody Videos video,Integer page) {
//        //保存热搜词
//        String record = video.getVideoDesc();
//        if (StringUtils.isNotBlank(record)) {
//            recordService.saveRecord(record);
//        }
//        //分页显示
//        if (page == null) {
//            page = 1;
//        }
//        //查询带有热搜词的视频
//        PagedResult result = videoService.getqueryVideos(page,PAGE_SIZE,record);
//        System.out.println(result.getRows());
//        return JSONResult.ok(result);
//    }
//
//    /**
//     * 对视频点赞
//     * @param userId
//     * @param videoId
//     * @return
//     */
//    @ApiOperation(value = "点赞视频", notes = "点赞接口")
//    @PostMapping("/like")
//    public JSONResult likeVideo(String userId, String videoId) {
//        if(userId == null || videoId == null) {
//            return JSONResult.errorMsg("请重新登录");
//        }
//        videoService.addLikeCounts(userId,videoId);
//        return JSONResult.ok();
//    }
//
//    /**
//     * 取消点赞视频
//     * @param userId
//     * @param videoId
//     * @return
//     */
//    @ApiOperation(value = "取消点赞", notes = "取消点赞接口")
//    @PostMapping("/unlike")
//    public JSONResult unlikeVideo(String userId, String videoId) {
//        if(userId == null || videoId == null) {
//            return JSONResult.errorMsg("请重新登录");
//        }
//        videoService.reduceLikeCounts(userId,videoId);
//        return JSONResult.ok();
//    }
//
//    /**
//     * 查询我的作品
//     * @param userId
//     * @param page
//     * @return
//     */
//    @PostMapping("/myvideo")
//    public JSONResult queryMyVideo(String userId, Integer page) {
//        if (StringUtils.isBlank(userId)) {
//            return JSONResult.ok();
//        }
//        if (page == null) {
//            page = 1;
//        }
//        PagedResult result = videoService.queryMyVideos(page,PAGE_SIZE + 1,userId);
//        return JSONResult.ok(result);
//    }
//
//    /**
//     * 查询我的收藏
//     * @param userId
//     * @param page
//     * @return
//     */
//    @PostMapping("/mylike")
//    public JSONResult queryMyLike(String userId, Integer page) {
//        if (StringUtils.isBlank(userId)) {
//            return JSONResult.ok();
//        }
//        if (page == null) {
//            page = 1;
//        }
//        PagedResult result = videoService.queryMyLikes(page,PAGE_SIZE + 1,userId);
//        return JSONResult.ok(result);
//    }
//
//    /**
//     * 查询我的关注
//     * @param userId
//     * @param page
//     * @return
//     */
//    @PostMapping("/myfollow")
//    public JSONResult queryMyFollow(String userId, Integer page) {
//        if (StringUtils.isBlank(userId)) {
//            return JSONResult.ok();
//        }
//        if (page == null) {
//            page = 1;
//        }
//        PagedResult result = videoService.queryMyFollows(page,PAGE_SIZE + 1,userId);
//        return JSONResult.ok(result);
//    }
}